import DictTypeTree, { DictTypeTreeRefType } from '@/components/DictTypeTree';
import SearchTablePage, { SearchTablePageRefType } from '@/components/SearchTablePage';
import { PERMISSION_KEY_DICT } from '@/constants';
import {
  addDict,
  deleteDictById,
  deleteDictsByIdList,
  getDictById,
  getDictList,
  updateDict,
} from '@/services/system/dict';
import { getDictTypeSelect } from '@/services/system/dictType';
import { optionsToValueEnum } from '@/utils/dataTransferUtils';

import { useModel, useRequest } from '@umijs/max';
import { message, theme } from 'antd';
import { Key, useRef, useState } from 'react';

const Dict: React.FC = () => {
  const {
    data: dictTypeSelect,
    error,
    refresh: refreshDictTypeSelect,
  } = useRequest(getDictTypeSelect);

  if (error) {
    message.error(error.message);
    console.error('error', error);
  }

  const dictTypeTreeActionRef = useRef<DictTypeTreeRefType>(null);
  const [selectParentIdList, setSelectParentIdList] = useState<Key[]>([]);
  const { useToken } = theme;
  const { token } = useToken();

  const { initialState } = useModel('@@initialState');
  const searchTablePageActionRef = useRef<SearchTablePageRefType>(null);

  return (
    <>
      <SearchTablePage<API.DictType>
        tableName="字典"
        getRowById={getDictById}
        updateRow={updateDict}
        addRow={addDict}
        deleteRowById={deleteDictById}
        deleteRowsByIdList={deleteDictsByIdList}
        getRowsByPage={getDictList}
        permissionKey={PERMISSION_KEY_DICT}
        onReset={() => {
          setSelectParentIdList([]);
          dictTypeTreeActionRef.current?.refresh();
        }}
        onModalFormOpen={() => {
          refreshDictTypeSelect();
        }}
        onAdd={() => {
          if (selectParentIdList.length > 0) {
            setTimeout(() => {
              searchTablePageActionRef.current?.setModalFormFieldValue(
                'dictType',
                selectParentIdList[0],
              );
            });
          }
        }}
        ref={searchTablePageActionRef}
        params={{
          dictType: selectParentIdList?.length > 0 ? selectParentIdList[0] : undefined,
        }}
        columns={[
          {
            title: '字典 ID',
            dataIndex: 'id',
            hideInTable: true,
            hideInSearch: true,
            hideInModal: true,
          },
          {
            title: '字典标签',
            dataIndex: 'label',
            showDetail: true,
            rules: [{ required: true }],
          },
          {
            title: '字典键值',
            dataIndex: 'value',
            ellipsis: true,
            rules: [{ required: true }],
          },
          {
            title: '字典类型',
            dataIndex: 'dictType',
            valueType: 'select',
            valueEnum: optionsToValueEnum(dictTypeSelect),
            options: dictTypeSelect,
            rules: [{ required: true, message: '请选择状态' }],
            hideInSearch: true,
          },
          {
            title: '字典颜色',
            dataIndex: 'color',
            hideInSearch: true,
          },
          {
            title: '字典CSS样式',
            dataIndex: 'cssStyle',
            hideInSearch: true,
            hideInTable: true,
          },
          {
            title: '状态',
            dataIndex: 'status',
            valueType: 'select',
            valueEnum: initialState?.system_common_status?.valueEnum,
            options: initialState?.system_common_status?.numOptions,
            rules: [{ required: true, message: '请选择状态' }],
          },
          {
            title: '备注',
            dataIndex: 'remark',
            hideInSearch: true,
            hideInTable: true,
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            hideInSearch: true,
            hideInModal: true,
          },
        ]}
        leftSide={
          <DictTypeTree
            onSelect={(selectedKeys) => {
              if (selectedKeys.length > 0 && selectedKeys[0] !== 'all') {
                setSelectParentIdList(selectedKeys);
              } else {
                setSelectParentIdList([]);
              }
            }}
            ref={dictTypeTreeActionRef}
            selectedKeys={selectParentIdList}
            style={{
              flex: '0 0 auto',
              minWidth: 160,
              maxWidth: 260,
              overflow: 'auto',
              backgroundColor: token.colorBgContainer,
              paddingTop: token.paddingContentHorizontalLG,
              paddingBottom: token.paddingContentHorizontalLG,
              paddingLeft: token.padding,
              paddingRight: token.padding,
              borderRadius: token.borderRadius,
              borderWidth: 1,
              borderStyle: 'solid',
              borderColor: token.colorBorderSecondary,
            }}
          />
        }
      />
    </>
  );
};

export default Dict;
